package com.yiyibook.controller;

import com.yiyibook.entity.ShoppingCar;
import com.yiyibook.service.ShoppingCarService;
import com.yiyibook.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 购物车信息 Controller
 *
 * @author yi.wu
 * @date 2019-10-14
 */
@RestController
@RequestMapping("/shoppingCar")
public class ShoppingCarController {

    @Autowired
    private ShoppingCarService shoppingCarService;

    @PostMapping("/insert")
    public Msg insert(@RequestBody ShoppingCar shoppingCar){
        // TODO: 2019/10/15 添加到购物车
        // 校验购物车中是否有该商品
        ShoppingCar sc = shoppingCarService.selectBookById(shoppingCar);
        if(sc!=null){
            // 购物车中有该商品
            // 图书数量增加
            sc.setBookBuyQuantity(sc.getBookBuyQuantity()+shoppingCar.getBookBuyQuantity());
            sc.setBookTotalAmount(sc.getBookBuyQuantity()*sc.getBookUnitPrice());
            // 更新数据库信息
            int i = shoppingCarService.updateByCondition(sc);
            if(i>0){
                return Msg.success().add("success","添加成功");
            }else {
                return Msg.fail().add("fail","网络波动，请重试！");
            }
        }else {
            // 购物车中没有该商品,新建购物车
            int i = shoppingCarService.insert(shoppingCar);
            if(i>0){
                return Msg.success().add("success","添加成功");
            }else {
                return Msg.fail().add("fail","网络波动，请重试！");
            }
        }
    }

    @GetMapping("/selectAll")
    public Msg selectAll(Integer memberId){
        return Msg.success().add("success",shoppingCarService.selectByMemberId(memberId));
    }

    @PatchMapping("update")
    public Msg update(@RequestBody ShoppingCar shoppingCar){
        // 处理数据
        shoppingCar.setBookTotalAmount(shoppingCar.getBookBuyQuantity()*shoppingCar.getBookUnitPrice());
        int i = shoppingCarService.updateByCarId(shoppingCar);
        if(i>0){
            return Msg.success().add("success","修改成功");
        }else {
            return Msg.fail().add("fail","网络波动，请重试！");
        }
    }

    @DeleteMapping("/delete")
    public Msg delete(Integer shopCarId){
        int i = shoppingCarService.deleteById(shopCarId);
        if(i>0){
            return Msg.success().add("success","删除成功");
        }else {
            return Msg.fail().add("fail","网络波动，请重试！");
        }
    }

}
